package com.example.test.dialogfactory;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import androidx.appcompat.app.AppCompatActivity;
import androidx.collection.ArraySet;
import easier.app.x.CommonCode;
import io.reactivex.rxjava3.android.schedulers.AndroidSchedulers;
import io.reactivex.rxjava3.annotations.NonNull;
import io.reactivex.rxjava3.core.Observable;
import io.reactivex.rxjava3.core.Observer;
import io.reactivex.rxjava3.disposables.Disposable;
import java.util.concurrent.TimeUnit;

public class MainActivity62 extends AppCompatActivity {

    private Button mClick;

    /**
     * 保存正在进行的请求
     */
    private static final ArraySet< String > tags = new ArraySet<>();

    private static boolean isRequesting( Context context, String tag ) {

        if ( tags.contains( tag ) ) {
            CommonCode.showToast( context, "正在请求中..." );
            return true;
        } else {
            tags.add( tag );
            return false;
        }
    }

    public static void start( Context context ) {

        Intent starter = new Intent( context, MainActivity62.class );
        context.startActivity( starter );
    }

    @Override
    protected void onCreate( Bundle savedInstanceState ) {

        super.onCreate( savedInstanceState );
        setContentView( R.layout.activity_main62 );
        initView();
    }

    private void initView() {

        mClick = (Button) findViewById( R.id.click );
        mClick.setOnClickListener( new OnClickListener() {
            @Override
            public void onClick( View v ) {

                Observable.just( "test" )
                    .delay( 5, TimeUnit.SECONDS )
                    .observeOn( AndroidSchedulers.mainThread() )
                    .subscribe( new Observer< String >() {
                        @Override
                        public void onSubscribe( @NonNull Disposable d ) {

                            if ( isRequesting( v.getContext(), "test" ) ) {
                                d.dispose();
                            }
                        }

                        @Override
                        public void onNext( @NonNull String s ) {

                            CommonCode.showToast( v.getContext(), s );
                            tags.remove( "test" );
                        }

                        @Override
                        public void onError( @NonNull Throwable e ) {

                            tags.remove( "test" );
                        }

                        @Override
                        public void onComplete() {

                        }
                    } );
            }
        } );
    }
}